/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ca.trader.beans.java;

import ca.trader.beans.enterprise.SaleBeanLocal;
import ca.trader.logger.TraderLogger;
import ca.trader.regions.Country;
import ca.trader.regions.Location;
import ca.trader.regions.Region;
import ca.trader.regions.RegionManager;
import ca.trader.sale.Sale;
import ca.trader.sale.SaleCategoryEnum;
import ca.trader.sale.SaleLookupQuery;
import ca.trader.sale.SaleLookupResult;
import ca.trader.startup.ServletContextManager;
import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author Ahsan
 */
public class SalesSearchBean
{

	 private static final String _className = SalesSearchBean.class.getName();
	 private SaleLookupQuery lookupQuery = new SaleLookupQuery();
	 private int pageNumber = -1;
	 private SaleLookupResult results;
	 private String errorMessage = "";
	 private boolean invalidInput = false;

	 public void setKeywords(String keywords)
	 {
		  final String _methodName = "setKeywords";

		  if (!invalidInput)
		  {
			   TraderLogger.logMethodEntry(_className, _methodName);

			   TraderLogger.logInfo(_className, _methodName, "Setting search keyword: " + keywords);

			   lookupQuery.setKeywords(keywords);
		  }
		  else
		  {
			   TraderLogger.logInfo(_className, _methodName, "Invalid input, doing nothing");
		  }

		  TraderLogger.logMethodExit(_className, _methodName);
	 }

	 public void setCategories(String[] categories)
	 {
		  final String _methodName = "setCategories";

		  TraderLogger.logMethodEntry(_className, _methodName);

		  if (!invalidInput)
		  {
			   TraderLogger.logInfo(_className, _methodName, "Setting search categories: " + categories);

			   ArrayList<SaleCategoryEnum> cCategories  = new ArrayList<> (categories.length);

			   for (String category:categories)
			   {
				    SaleCategoryEnum categoryEnum = SaleCategoryEnum.getSaleCategoryByName(category);
				    if (categoryEnum == null)
				    {
						errorMessage = '"' + category + "\" is not a valid category";
						invalidInput = true;

						TraderLogger.logWarning(_className, _methodName, errorMessage);
						TraderLogger.logMethodExit(_className, _methodName);

						return;
				    }
			   }

			   lookupQuery.setCategories(cCategories);
		  }
		  else
		  {
			   TraderLogger.logInfo(_className, _methodName, "Invalid input, doing nothing");
		  }

		  TraderLogger.logMethodExit(_className, _methodName);
	 }

	 public void setCountry(String countryName)
	 {
		  final String _methodName = "setCountry";

		  TraderLogger.logMethodEntry(_className, _methodName);

		  if (!invalidInput)
		  {
			   TraderLogger.logInfo(_className, _methodName, "Setting search country: " + countryName);

			   RegionManager regionManager = ServletContextManager.getRegionManager();


			   Location enteredLocation = new Location();
			   Country c = regionManager.getCountry(countryName);

			   if (c == null)
			   {
				    errorMessage = '"' + countryName + "\" is not a valid country";
				    invalidInput = true;

				    TraderLogger.logWarning(_className, _methodName, errorMessage);
				    TraderLogger.logMethodExit(_className, _methodName);

				    return;
			   }

			   enteredLocation.setCountry(c);
			   lookupQuery.setLocation(enteredLocation);
		  }
		  else
		  {
			   TraderLogger.logInfo(_className, _methodName, "Invalid input, doing nothing");
		  }

		  TraderLogger.logMethodExit(_className, _methodName);

	 }

	 public void setRegion(String regionName)
	 {
		  final String _methodName = "setRegion";

		  TraderLogger.logMethodEntry(_className, _methodName);

		  if (!invalidInput)
		  {
			   if (lookupQuery.getLocation() == null)
			   {
				    TraderLogger.logWarning(_className, _methodName, "Country not entered, exiting");
				    TraderLogger.logMethodExit(_className, _methodName);
				    throw new IllegalStateException("Must enter country first!");
			   }

			   TraderLogger.logInfo(_className, _methodName, "Setting search region: " + regionName);

			   Country userCountry = lookupQuery.getLocation().getCountry();

			   Region r = userCountry.getRegion(regionName);
			   if (r == null)
			   {
				    errorMessage = '"' + regionName + "\" is not a valid region";
				    invalidInput = true;

				    TraderLogger.logWarning(_className, _methodName, errorMessage);
				    TraderLogger.logMethodExit(_className, _methodName);

				    return;
			   }

			   lookupQuery.getLocation().setRegion(r);
		  }
		  else
		  {
			   TraderLogger.logInfo(_className, _methodName, "Invalid input, doing nothing");
		  }

		  TraderLogger.logMethodExit(_className, _methodName);

	 }

	 public void setCity(String cityName)
	 {
		  final String _methodName = "setCity";

		  TraderLogger.logMethodEntry(_className, _methodName);

		  if (!invalidInput)
		  {
			   if (lookupQuery.getLocation() == null || lookupQuery.getLocation().getRegion() == null)
			   {
				    TraderLogger.logWarning(_className, _methodName, "Country or region not entered, exiting");
				    TraderLogger.logMethodExit(_className, _methodName);
				    throw new IllegalStateException("Must enter country and region first!");
			   }


			   Region userRegion = lookupQuery.getLocation().getRegion();
			
			   if (!userRegion.containsCity(cityName))
			   {
				    errorMessage += '"' + cityName + "\" is not a valid city";
				    invalidInput = true;

				    TraderLogger.logWarning(_className, _methodName, errorMessage);
				    TraderLogger.logMethodExit(_className, _methodName);

				    return;
			   }

			   TraderLogger.logInfo(_className, _methodName, "Setting search city: " + cityName);

			   lookupQuery.getLocation().setCity(cityName);
		  }
		  else
		  {
			   TraderLogger.logInfo(_className, _methodName, "Invalid input, doing nothing");
		  }

		  TraderLogger.logMethodExit(_className, _methodName);

	 }

	 public void setPageNumber(String sPageNumber)
	 {
		  final String _methodName = "setPageNumber";
		  TraderLogger.logWarning(_className, _methodName, "Setting page number: " + sPageNumber);
		  try
		  {
			   pageNumber = Integer.parseInt(sPageNumber);
		  }
		  catch (NumberFormatException ex)
		  {
			   pageNumber = -1;
			   TraderLogger.logWarning(_className, "setPageNumber", "Error setting page number: " + sPageNumber);
		  }
	 }

	 public void searchResults()
	 {
		  final String _methodName = "getResults";


		  TraderLogger.logMethodEntry(_className, _methodName);
		  if (!invalidInput)
		  {
			   try
			   {
				    SaleBeanLocal saleBean = BeanUtils.getSaleBean();

				    TraderLogger.logMethodExit(_className, _methodName);

				    results = saleBean.getSalesByQuery(lookupQuery, BeanConsts.SALES_PER_PAGE * (pageNumber - 1), BeanConsts.SALES_PER_PAGE);

			   }
			   catch (Exception e)
			   {
				    TraderLogger.logSevere(_className, _methodName, "Unknown exception ", e);
			   }
		  }
		  else
		  {
			   TraderLogger.logInfo(_className, _methodName, "Invalid input, doing nothing");
		  }

		  TraderLogger.logMethodExit(_className, _methodName);

	 }

	 public boolean isResultsFound()
	 {
		  return !invalidInput && results != null && results.getResults().size() > 0;
	 }

	 public String getTotalCount()
	 {
		  if (!isResultsFound())
		  {
			   throw new IllegalStateException("A sale has not been found.");
		  }
		  return ((int) Math.ceil(((double) results.getTotalCount()) / ((double) BeanConsts.SALES_PER_PAGE))) + "";

	 }

	 public List<Sale> getResults()
	 {
		  if (!isResultsFound())
		  {
			   throw new IllegalStateException("A sale has not been found.");
		  }
		  return results.getResults();
	 }

	 public String getErrorMessage()
	 {
		  if (invalidInput)
		  {
			   return errorMessage;
		  }
		  else if (!isResultsFound())
		  {
			   return "No results found";
		  }

		  throw new IllegalStateException("No error message");

	 }

}
